const invalidVal = '--';

/**
 * 每隔三位数用逗号隔开，小数点后面不管多少位都保留
 * @param num 数字或数字字符串
 * @returns 每隔三位数用逗号隔开的字符串
 */
export const getFormatNum = (num: string | number): string => {
    //取小数，三行逗号隔开，小数点后面不管多少位都保留
    try {
        const [beforeDot, afterDot] = (num + '').split('.');
        return parseFloat(beforeDot).toLocaleString() + (afterDot ? `.${afterDot}` : '');
    } catch (e) {
        console.log(`e = ${e}`);
        return num + '';
    }
};
/**
 * 数字扩大
 * @param num 数字
 * @param length 扩大倍数有几个0，默认为4，扩大10000
 * @returns 扩大后的数字
 */
export const num10xMax = (num, length = 4): number => {
    num = num + '';
    const numArr = num.split('.');
    let afterDot = numArr.length === 2 ? numArr[1] : '';
    if (afterDot) {
        afterDot = afterDot.slice(0, length);
    }
    //自动补0
    while (afterDot.length < length) {
        afterDot = afterDot + '0';
    }
    num = parseInt(numArr[0] + afterDot);
    return num;
};
/**
 * 数字缩小
 * @param num 数字
 * @param length 缩小倍数有几个0，默认为4，缩小10000倍
 * @returns 缩小后的数字
 */
export const num10xMin = (num, length = 4): number => {
    num = Number(num);
    if (num) {
        num = num / Math.pow(10, length);
    }
    const numArr = (num + '').split('.');
    if (numArr.length === 2) {
        num = numArr[0] + '.' + numArr[1].slice(0, length);
    }
    return num;
};
/**
 * 数字千分位格式化，每隔三位用逗号隔开
 * @param num 要处理的数字
 * @param decimal 保留几位小数
 * @param defaultVal 默认值
 * @returns
 */
export const numberToThousands = (num: number | string, decimal = 2, defaultVal: string = invalidVal) => {
    //异常数据处理
    if (!num && num !== 0) {
        return defaultVal;
    }
    //统一数据类型
    num = parseFloat(num.toString());
    if (isNaN(num)) {
        return defaultVal;
    }
    //分别取小数部分和整数部分
    let intVal = Math.floor(num).toString();
    //小数部分只做位数保留处理
    const decimalVal = (num % 1).toFixed(decimal);
    const singleVal = decimalVal.substr(0, 1);
    intVal = (Number(intVal) + Number(singleVal)).toString();
    //整数部分千分位处理
    intVal = intVal.replace(/(\d{1,3})(?=(\d{3})+$)/g, function (s) {
        return s + ',';
    });
    //整合小数部分和整数部分
    return intVal + decimalVal.substr(1);
};
/**
 * 金额干分位字符转金额数字
 * @param val 数字
 * @returns 金额
 */
export const changeNumber = (val: number | string): string => {
    if (val) {
        const a = (val + '').replace(/,/g, '');
        return Number(a).toFixed(2);
    } else {
        return Number(0).toFixed(2);
    }
};
/**
 * 精确取小数位数
 * @param value 数字
 * @param precision 保留几位小数
 * @returns 处理后的数字
 */
export const toFixed = (value, precision: number) => {
    precision = checkPrecision(precision, 0);
    const exponentialForm = Number(unformat(value) + 'e' + precision);
    const rounded = Math.round(exponentialForm);
    const finalResult = Number(rounded + 'e-' + precision).toFixed(precision);
    return finalResult;

    // 检查位数必须为数字且为正数
    function checkPrecision(val: number, base: number) {
        val = Math.round(Math.abs(val));
        return isNaN(val) ? base : val;
    }

    // Map 方法
    function map(obj, iterator, context?) {
        const nativeMap = Array.prototype.map;
        const results = [];
        let i;
        let j;
        if (!obj) return results;
        if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
        for (i = 0, j = obj.length; i < j; i++) {
            results[i] = iterator.call(context, obj[i], i, obj);
        }
        return results;
    }

    function unformat(_value, decimal?: string | undefined) {
        if (Array.isArray(_value)) {
            return map(_value, function (val) {
                return unformat(val, decimal);
            });
        }
        _value = _value || 0;
        if (typeof _value === 'number') return _value;
        decimal = decimal || '.';
        const regex = new RegExp('[^0-9-' + decimal + ']', 'g'),
            unformatted = parseFloat(
                ('' + _value)
                    .replace(/\((?=\d+)(.*)\)/, '-$1')
                    .replace(regex, '')
                    .replace(decimal, '.'),
            );
        return !isNaN(unformatted) ? unformatted : 0;
    }
};
